#!/usr/bin/env bash

set -o errexit

if [[ -t 1 ]]
then
    exec 2>&1 | ts '%X %Z'
fi

exec 220>/tmp/.RunIncrementalJSONDump.lock || exit 1
# Will be automatically released when the script exits.
flock -n 220 || { echo "Failed to obtain lock. Another instance is running?" >&2; exit 1; }

# This is to help with disk space monitoring - run "df" before and after
echo "Disk space when RunIncrementalJSONDump starts:" ; df -m
trap 'echo "Disk space when RunIncrementalJSONDump ends:" ; df -m' 0

MB_SERVER_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../" && pwd)
cd "$MB_SERVER_ROOT"

source admin/config.sh

. ./admin/functions.sh
make_temp_dir

# We use "$TEMP_DIR" directly as an rsync source below, which means its
# permissions are transferred onto the remote directory as well. This sets
# something more permissive than the default 0700, which allows the uwsgi
# processes serving the incremental JSON dumps to be able to read them.
chmod 755 "$TEMP_DIR"

# Create a clean test database from which to dump foreign keys.
export REPLICATION_TYPE=3 # RT_STANDALONE
./script/create_test_db.sh TEST

FK_DUMP="$TEMP_DIR"/foreign_keys
./script/dump_foreign_keys.pl \
    --database TEST \
    --output "$FK_DUMP"

echo Making incremental JSON dumps
./admin/DumpIncrementalJSON \
    --output-dir "$TEMP_DIR" \
    --compress \
    --database READWRITE \
    --foreign-keys-dump "$FK_DUMP" \
    || exit $?

cleanup() {
    rm -f "$FK_DUMP"
    # We've clobbered the trap set by `make_temp_dir`. Reinstate it.
    rmdir "$TEMP_DIR"
}
trap cleanup EXIT

# Was a dump created?
shopt -s nullglob
DUMP_FILE=`echo -n "$TEMP_DIR"/json-dump-*/*.tar.xz`
shopt -u nullglob

# Incremental JSON dumps are synced to a Docker volume on the same host as
# the metabrainz.org container.
if [ "$DUMP_FILE" ]
then
    echo Copying incremental json dumps to backup dir
    chown "$JSON_DUMP_USER:$JSON_DUMP_GROUP" "$TEMP_DIR"/json-dump-*/*
    chmod "$JSON_DUMP_FILE_MODE" "$TEMP_DIR"/json-dump-*/*

    retry rsync \
        --archive \
        --rsh "ssh -i $RSYNC_INCREMENTAL_JSON_DUMPS_KEY -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -p $RSYNC_INCREMENTAL_JSON_DUMPS_PORT" \
        --verbose \
        "$TEMP_DIR"/ \
        brainz@$RSYNC_INCREMENTAL_JSON_DUMPS_HOST:./

    rm -rf "$TEMP_DIR"/*
fi

# eof
